package com.pearlsoft.webapp.core.web.session;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pearlsoft.webapp.core.web.util.HttpUtil;

/**
 * 
 * @Creator haitingr
 * @Create-Date 2010-12-28
 */
public class SessionTracker {
	protected static Log logger = LogFactory.getLog(SessionTracker.class);

	protected static final ThreadLocal<HttpSession> current_session = new ThreadLocal<HttpSession>();

	protected static final Map<String, HttpSession> online_session = new ConcurrentHashMap<String, HttpSession>();

	public static void login(HttpSession session) {
		online_session.put(session.getId(), session);
	}

	public static void logout(HttpSession session) {
		online_session.remove(session.getId());
	}

	public static void trackCurrentSession(HttpServletRequest request) {
		current_session.set(HttpUtil.getSession(request));
	}

	public static void bind(HttpServletRequest request, SessionProfile sp) {
		HttpUtil.getSession(request).setAttribute(SessionProfile.PROFILE_TAG, sp);
	}

	public static SessionProfile currentUserProfileVO() {
		HttpSession session = current_session.get();
		if (session == null) {
			return null;
		}

		return HttpUtil.getUserProfile(session);
	}

	public static boolean validateRequest(HttpServletRequest request) {
		HttpSession session = HttpUtil.getSession(request);
		if (session == null) {
			return false;
		}
		return online_session.containsKey(session.getId());
	}
}
